package com.hmall.gateway.filter;


import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter , Ordered {

    private final  AuthProperties authProperties;

    private  final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求路径
        String path = request.getPath().toString();
        // 白名单
        List<String> excludePaths = authProperties.getExcludePaths();
        //判断当前请求路径是否在白名单中
        for ( String excludePath : excludePaths){
            boolean match = antPathMatcher.match(excludePath, path);
            if (match){
                return chain.filter(exchange);
            }
        }

        //获取token
        String token = exchange.getRequest().getHeaders().getFirst("authorization");
        if (token == null){
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //如果token不为空则校验token
        Long userid  = null;
        try {
            userid = jwtTool.parseToken(token);
        } catch (Exception e) {
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //  5.如果有效，传递用户信息
        exchange.getRequest().mutate().header("user-info", userid.toString());
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
